package com.bdth.controller;

import com.bdth.model.Department;
import com.bdth.model.PageModel;
import com.bdth.model.User;
import com.bdth.model.ZTreeNode;
import com.bdth.service.IDepartmentService;
import com.bdth.service.IDeviceBindService;
import com.bdth.service.IDeviceService;
import com.bdth.service.IMessageService;
import com.bdth.utils.DateUtil;
import com.bdth.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Controller
@RequestMapping("/message")
public class MessageController extends BaseController {

	@Autowired
	private IMessageService messageService;

	private Boolean updateNode = false;

	@Autowired
	private IDepartmentService departmentService;

	@Autowired
	private IDeviceService deviceService;

	@Autowired
	private IDeviceBindService deviceBindService;

	Map<Integer, Department> depMap = new HashMap<Integer, Department>();

	private List<ZTreeNode> zTreeNodeList = new ArrayList<ZTreeNode>();

	private static String KEY_MESSAGE_MAP = "key_message_map";

	protected static final Logger logger = LoggerFactory.getLogger(MessageController.class);

	@RequestMapping("/multicastMessage")
	public ModelAndView multicastMessage(HttpServletRequest request)
			throws Exception {
		return forword("/message/multicastMessage");
	}

	@RequestMapping("/informationMessage")
	public ModelAndView informationMessage(HttpServletRequest request)
			throws Exception {
		return forword("/message/informationMessage");
	}

	/**
	 * json 列表页面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/dataList")
	public void dataList(PageModel pageModel, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List dataList = getDataList(pageModel, request, true);
	/*	String today1 = "2018-01-11";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = format.parse(today1);
		System.out.println(DateUtil.GetWeekOfYear(date));*/
		//获得结果集条总数
		PageInfo pageList = new PageInfo(dataList);
		//设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", pageList.getTotal());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}

	// 生成设备树菜单
	@RequestMapping("/getDeviceTree")
	public void getDeviceTree(HttpServletRequest request, HttpServletResponse response, Boolean updateNode, int type) {
		this.updateNode = updateNode;
		zTreeNodeList.clear();
		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {
			Map<String, Object> mapDep = new HashMap<String, Object>();
			User user = SessionUtils.getUser(request);

			List<Integer> depIds = getDepIds(user.getDepId());
			mapDep.put("depIds", depIds);

			// 用户分配的车队
			List<Department> depSet = departmentService.queryByMapList(mapDep);
			List<Department> depList = new ArrayList<Department>();

			Map<Integer, Integer> nodeMap = new HashMap<Integer, Integer>();
			if (depSet != null) {
				for (Department dep : depSet) {
					depList.add(dep);
				}
			}

			List<Department> allDepList = departmentService.queryByMapList(new HashMap());

			for (Object obj : allDepList) {
				Department dep = (Department) obj;
				depMap.put(dep.getId(), dep);
			}
			createDeviceTreeNode(request, type);// 创建设备树节点
			// 生成部门树
		/*	Collections.sort(depList, new Comparator<Department>() {
				public int compare(Department o1, Department o2) {
					if (o1.getDepName() == null)
						return -1;

					return o1.getDepName().compareTo(o2.getDepName());
				}

			});*/
			for (Department d : depList) {
				Department dep = depMap.get(d.getId());
				if (dep == null)
					continue;
				setTreeData(dep, request);
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		resultMap.put("TreeDataIndex", zTreeNodeList);
		HtmlUtil.writerJson(response, resultMap);
	}


	/**
	 * 创建设备树节点
	 */
	private void createDeviceTreeNode(HttpServletRequest request, int type) throws Exception {
		String path = request.getContextPath();
		Date start = new Date();
		Map<String, Object> params = new HashMap<String, Object>();
		User user = SessionUtils.getUser(request);
		List result = null;
		//params.put("userId", user.getId());
		List<Integer> depIds = getDepIds(user.getDepId());
		params.put("depIds", depIds);
		params.put("typeID", type);
		result = deviceService.queryDeviceTree(params);
		if (result == null)
			result = new ArrayList();
		List<String> simNos = new ArrayList<String>();
		for (Object o : result) {
			Map rowData = (Map) o;
			String simNo = "realData_" + rowData.get("SimNo");
			simNos.add(simNo);
		}

		for (Object obj : result) {
			Map rowData = (Map) obj;
			String simNo = "" + rowData.get("SimNo");
			int vehicleId = (Integer) rowData.get("id");
			int depId = (Integer) rowData.get("DepId");
			String equipName = "" + rowData.get("equipName");
			String tid = "v" + vehicleId;
			String parentNodeId = "dep" + depId;
			ZTreeNode mzTn = new ZTreeNode(tid, equipName, parentNodeId, path + "/images/device.png", simNo);

			zTreeNodeList.add(mzTn);

			Department dep = depMap.get(depId);
			while (dep != null) {
				dep.setTotalNum(dep.getTotalNum() + 1);
				dep = depMap.get(dep.getParentDepId());
			}

		}
		Date end = new Date();

		//log.error("实时数据刷新耗时:" + seconds + ",条数：" + result.size());
	}

	private void setTreeData(Department dep, HttpServletRequest request) {
		String path = request.getContextPath();
		try {
			String depNodeId = "dep" + dep.getId();
			int parentId = dep.getParentDepId();
			// parentId = parentId > 0 ? ("dep_"+parentId) : 1;
			String strParentNodeId = "dep" + parentId;
			ZTreeNode mzTn = new ZTreeNode(depNodeId, dep.getDepName(),
					strParentNodeId, path + "/images/ztree/dep.png", false);

			zTreeNodeList.add(mzTn);

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}


	/**
	 * json 列表页面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/dataBindList")
	public void dataBindList(PageModel pageModel, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String equipName = request.getParameter("equipName");
		String simNo = request.getParameter("simNo");
		String parentSims = "" + request.getParameter("parentSims");
		String depIdSearch = "" + request.getParameter("depIdSearch");
		map.put("equipName", equipName);
		map.put("simNo", simNo);
		User user = SessionUtils.getUser(request);
		if (!StringUtil.isEmptyWithNullStr(depIdSearch) && !"0".equals(depIdSearch)) {
			List<Integer> depIds = getDepIds(Integer.valueOf(depIdSearch));
			map.put("depIds", depIds);
		} else {
			List<Integer> depIds = getDepIds(user.getDepId());
			map.put("depIds", depIds);
		}
		List parentSimList = new ArrayList<>();
		String[] parentSimss = parentSims.split(",");
		for (String s : parentSimss) {
			parentSimList.add(s);
		}

		map.put("parentSims", parentSimList);
		//紧跟着的第一个查询方法会被分页
		PageHelper.startPage(pageModel.getPage(), pageModel.getRows());
		List<Map> dataList = deviceBindService.queryBindDataByMapList(map);
		//获得结果集条总数
		PageInfo pageList = new PageInfo(dataList);
		//设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", pageList.getTotal());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}


	public List getDataList(PageModel pageModel, HttpServletRequest request, boolean pageFlag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map> dataList = null;
		String sendSim = request.getParameter("sendSim");
		String recSim = request.getParameter("recSim");
		String startTime = "" + request.getParameter("startTime");
		String endTime = "" + request.getParameter("endTime");
		String sendEquipName = request.getParameter("sendEquipName");
		String recEquipName = request.getParameter("recEquipName");
		String dataListForExport = request.getParameter("dataListForExport");
		if (StringUtil.isEmptyWithNullStr(startTime)) {
			startTime = DateUtil.convertDateToYearMonthDay(new Date());
			endTime = DateUtil.convertDateToYearMonthDay(new Date());
		} else {
			startTime = startTime.substring(0, 10).replace("-", "");
			endTime = endTime.substring(0, 10).replace("-", "");
		}
		String today = DateUtil.getFomartDate(new Date(), "yyyyMMdd");
		if (endTime.compareTo(today) > 0)
			endTime = today;
		map.put("sendSim", sendSim);
		map.put("recSim", recSim);
		map.put("sendEquipName", sendEquipName);
		map.put("recEquipName", recEquipName);
		String tableName1 = "tb_Message" + startTime;
		String tableName2 = "tb_Message" + endTime;
		map.put("tableName1", tableName1);
		map.put("tableName2", tableName2);

		map.put("startTime", request.getParameter("startTime"));
		map.put("endTime", request.getParameter("endTime"));
		map.put("dataListForExport", dataListForExport);
		User user = SessionUtils.getUser(request);
		List<Integer> depIds = getDepIds(user.getDepId());
		map.put("depIds", depIds);
		if (pageFlag) {
			//紧跟着的第一个查询方法会被分页
			PageHelper.startPage(pageModel.getPage(), pageModel.getRows());
		}
		if (tableName1.equals(tableName2) == false) {
			dataList = messageService.queryMapDataByMapListIn2Days(map);
		} else {
			dataList = messageService.queryMapDataByMapList(map);
		}
		return dataList;
	}


	/**
	 * 导出历史数据
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/exportHisMessage")
	public void exportHisMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			List dataList = getDataList(null, request, false);
			String sendEquipName = request.getParameter("sendEquipName");
			String recEquipName = request.getParameter("recEquipName");

			String separator = File.separator;
			String xlsFile = System.getProperty("csc2.root") + separator
					+ "excel" + separator
					+ "hisMessageModel.xlsx";
			String filename = "报文短信数据.xlsx";// 设置下载时客户端Excel的名称
			OutputStream ouputStream = null;
			Workbook workbook = WorkbookFactory.create(new FileInputStream(xlsFile));
			Sheet sheet = workbook.getSheetAt(0);
			Font headerFont = workbook.createFont(); // 字体
			headerFont.setFontHeightInPoints((short) 11);
			headerFont.setFontName("Arial");
			int count = 0;
			// 设置数据行

			Row row1 = sheet.getRow(0);
			Cell cell1 = row1.getCell(1);
			cell1.setCellValue(sendEquipName);
			Cell cell2 = row1.getCell(3);
			cell2.setCellValue(recEquipName);
			Row row2 = sheet.getRow(1);
			Cell cell3 = row2.getCell(1);
			cell3.setCellValue(request.getParameter("startTime"));
			Cell cell4 = row2.getCell(3);
			cell4.setCellValue(request.getParameter("endTime"));
			CellStyle cellStyle = workbook.createCellStyle();

			cellStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT);


			cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平布局：居中
			cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
			cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
			cellStyle.setBottomBorderColor(new XSSFColor(java.awt.Color.BLACK).getIndexed());
			cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
			cellStyle.setLeftBorderColor(new XSSFColor(java.awt.Color.BLACK).getIndexed());
			cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
			cellStyle.setRightBorderColor(new XSSFColor(java.awt.Color.BLACK).getIndexed());
			cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
			cellStyle.setTopBorderColor(new XSSFColor(java.awt.Color.BLACK).getIndexed());
			cellStyle.setFont(headerFont);
			cellStyle.setWrapText(true);

			int i = 0;
			for (Object obj : dataList) {
				Map r = (Map) obj;
				try {
					Object[] data = {r.get("sendEquipName") + "",
							r.get("sendDepname") + "",
							r.get("recEquipName") + "",
							r.get("recDepname") + "",
							DateUtil.getPlusTime(DateUtil.getDateFromString(r.get("sendTime") + "")),
							r.get("message") + ""};
					ExportExcelUtil.writeRowLine(workbook,
							sheet, cellStyle,
							headerFont,
							i + 3,
							data);
					i++;
				} catch (Exception e) {
					logger.error(e.getMessage());
					continue;
				}
			}


			filename = ExportExcelUtil.encodeFilename(filename, request);
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.addHeader("Content-Disposition", "attachment;filename=" + filename);
			ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();

		} catch (IOException e) {
			logger.error(e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

	}

	// 将短信数据发给页面弹窗显示
	@RequestMapping("/message")
	public void message(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> context = new HashMap<String, Object>();
		Hashtable messageData = new Hashtable();
		try {
			Hashtable parameters = new Hashtable();
			String tableName = "tb_Message"
					+ DateUtil.getFomartDate(new Date(), "yyyyMMdd");
			parameters.put("tableName1", tableName);// 报警数据是一个月一张表
			parameters.put("startTime", DateUtil.getFomartDate(new Date(new Date().getTime() - 600000), "yyyy-MM-dd HH:mm:ss"));
			parameters.put("endTime", DateUtil.getFomartDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
			User user = SessionUtils.getUser(request);
			if (user == null) {
				String path = request.getContextPath();
				response.sendRedirect(path + "/login");
			}
			List<Integer> depIds = getDepIds(user.getDepId());
			parameters.put("depIds", depIds);
			parameters.put("dataListForExport", true);
			try {
				List result = messageService.queryMapDataByMapList(parameters);
				result = filterMessageResult(result, request, depIds);
				messageData.put("message", result);
			} catch (Exception ex) {
				logger.error(ex.getMessage(), ex);
			}
			context.put(SUCCESS, true);
			context.put("data", messageData);

			HtmlUtil.writerJson(response, context);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}


	/**
	 * 已经短信的，将不再重复弹出
	 *
	 * @param alarmList
	 * @return
	 */

	private List filterMessageResult(List alarmList, HttpServletRequest request, List depIds) throws Exception {
		Map<String, Date> messageMap = getMessageMap(request);
		List result = new ArrayList();
		for (Object obj : alarmList) {
			Map rowData = (Map) obj;
			int messageId = (int) rowData.get("id");
			boolean sendDepidFlag = false;
			boolean recDepidFlag = false;
			if (rowData.get("sendDepid") != null) {
				int sendDepid = (int) rowData.get("sendDepid");
				sendDepidFlag = isAuthorizedDep(sendDepid, request, depIds);
			}
			if (rowData.get("recDepid") != null) {
				int recDepid = (int) rowData.get("recDepid");
				recDepidFlag = isAuthorizedDep(recDepid, request, depIds);
			}

			// 车辆不是用户所管辖的单位
			if ((sendDepidFlag == false) && (recDepidFlag == false))
				continue;

			String key = "_" + messageId;
			// 只推送未推送的短信，已经推送到前台的，不再推送。
			if (messageMap.containsKey(key) == false) {
				messageMap.put(key, new Date());

				//convert(rowData);
				result.add(rowData);

			}

		}
		//System.out.println(result);
		return result;
	}


	/**
	 * 已经短信的记录，保存在Session中，避免重复报警
	 *
	 * @return
	 */
	public Map<String, Date> getMessageMap(HttpServletRequest request) {
		Map<String, Date> messageMap = (HashMap<String, Date>) request.getSession(true).getAttribute(
				KEY_MESSAGE_MAP);
		if (messageMap == null) {
			messageMap = new HashMap<String, Date>();
			request.getSession(true).setAttribute(KEY_MESSAGE_MAP, messageMap);
		}
		return messageMap;
	}

	protected boolean isAuthorizedDep(int depId, HttpServletRequest request, List depIds) throws Exception {
		if (depIds.contains(depId)) {
			return true;
		} else {
			return false;
		}
	}
}
